package com.westinyang.javaapp.slice;

import com.westinyang.javaapp.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class MainAbilitySlice extends AbilitySlice {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Button button = (Button) findComponentById(ResourceTable.Id_button_login);
        // 为按钮设置点击事件回调
        button.setClickedListener(component -> {
            TextField textFieldUsername = (TextField)findComponentById(ResourceTable.Id_text_field_username);
            String username = textFieldUsername.getText();
            TextField textFieldPassword = (TextField)findComponentById(ResourceTable.Id_text_field_pwssword);
            String password = textFieldPassword.getText();
            // ...
            boolean res = login(username, password);
            String hint = getLoginHint(res);
            // ...
            new ToastDialog(getContext())
                    .setText(hint)
                    .setDuration(2000)
                    //.setAlignment(LayoutAlignment.CENTER)
                    .setOffset(0, 200)
                    .show();
        });
    }

    public boolean login(String username, String password) {
        return "admin".equals(username) && "123456".equals(password);
    }

    public String getLoginHint(boolean isSuccess) {
        return isSuccess ? "登录成功" : "登录失败";
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackPressed() {
        exit();
    }

    // 两次返回键退出
    private long exitTime = 0;
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            new ToastDialog(getContext())
                    .setText("再按一次返回键退出")
                    .setDuration(2000)
                    //.setAlignment(LayoutAlignment.CENTER)
                    .setOffset(0, 200)
                    .show();
            exitTime = System.currentTimeMillis();
        } else {
            // finish();
            System.exit(0);
        }
    }

}
